package com.suse.common.util.response;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.suse.common.util.io.IoUtil;
import com.suse.common.util.request.RequestUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>
 * 响应工具类
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-09-05 23:54
 */
public class ResponseUtil {

    public static HttpServletResponse getResponse() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (ObjectUtil.isNull(requestAttributes)) {
            return null;
        }
        return requestAttributes.getResponse();
    }

    public static void sendJSON(Object data) {
        HttpServletResponse response = getResponse();
        if (ObjectUtil.isNull(response)) {
            return;
        }
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.print(JSONObject.toJSONString(data));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            IoUtil.close(writer);
        }
    }

    public static void sendRedirect(String path) {
        HttpServletRequest request = RequestUtil.getRequest();
        HttpServletResponse response = getResponse();
        if (ObjectUtil.isNull(request)) {
            return;
        }
        if (ObjectUtil.isNull(response)) {
            return;
        }
        try {
            response.sendRedirect(request.getContextPath() + path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
